package search;

/**
 * @Author leecho
 * @Date: 2021/10/20 12:19
 * @Version 1.0
 */


/*
* 思路
* - 找到中点值
* - 目标值与中点值
* - 缩小寻找范围，继续找到缩小范围后的中点值
* - 比较 缩小 缩小 最后找到或返回空
* */
public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {1,3,4,5,66,77,87};
        BinarySearch binarySearch = new BinarySearch();
        int i = binarySearch.binarySearch(arr, 0, arr.length - 1, 77);
        System.out.println(i);

    }

    public int binarySearch(int[] arr, int left, int right, int findVal){
        if (left > right)
            return -1;
        int mid = (left+right) / 2;

        if (findVal > arr[mid]){
            return binarySearch(arr,mid+1,right,findVal);
        } else if (findVal < arr[mid]){
            return binarySearch(arr,right,mid-1,findVal);
        } else {
            return mid;
        }
    }

}
